package cn.com.cifi.mars.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.com.cifi.mars.bean.dto.SysRoleOrgDataPermissionDto;
import cn.com.cifi.mars.bean.vo.sys.req.SaveSysRoleOrgDataPermissionReqParam;
import cn.com.cifi.mars.constant.HrOrgTypeEunm;
import cn.com.cifi.mars.entity.common.SysRoleOrgDataPermission;
import cn.com.cifi.mars.mapper.mars.SysRoleOrgDataPermissionMapper;
import cn.com.cifi.mars.service.SysRoleOrgDataPermissionService;
import cn.com.cifi.mars.util.UUIDUtils;

/**
 * <p>
 * 角色组织机构数据权限关联表 服务实现类
 * </p>
 *
 * @author yyd
 * @since 2019-09-19
 */
@Service
public class SysRoleOrgDataPermissionServiceImpl extends ServiceImpl<SysRoleOrgDataPermissionMapper, SysRoleOrgDataPermission> implements SysRoleOrgDataPermissionService {

	@Autowired
	private SysRoleOrgDataPermissionMapper sysRoleOrgDataPermissionMapper;

	/**
	 * 角色管理-添加角色组织机构数据权限信息
	 */
	@Transactional
	@Override
	public int addDataPermission(SaveSysRoleOrgDataPermissionReqParam param) {
		//先删除角色组织机构关联数据
		sysRoleOrgDataPermissionMapper.deleteRoleId(param.getRoleId());
		//添加关联关系
		int num=0;
		for (String orgid : param.getOrgids()) {
			SysRoleOrgDataPermission bean=new SysRoleOrgDataPermission();
			bean.setOrgid(orgid);
			bean.setRoleId(param.getRoleId());
			bean.setId(UUIDUtils.create());
			num=sysRoleOrgDataPermissionMapper.insert(bean);
		}
		return num;
	}

	/**
	 * 角色管理-显示角色组织机构数据权限树
	 */
	@Override
	public JSONArray querySysRoleOrgDataPermissionTree(String roleId) {
		List<SysRoleOrgDataPermissionDto> list=sysRoleOrgDataPermissionMapper.selectRoleOrgDataPermissionTree(roleId,HrOrgTypeEunm.ORG_32.getKey());
		
		
		List<SysRoleOrgDataPermissionDto> listTree=buildTree(list,"00000000");
		JSONArray trssJson= JSONArray.parseArray(JSON.toJSONString(listTree));
		return trssJson;
	}
	
	/**
	 * 递归子节点
	 * @param list
	 * @param parentId
	 * @return
	 */
	public static List<SysRoleOrgDataPermissionDto> buildTree(List<SysRoleOrgDataPermissionDto> list,String parentId){
		List<SysRoleOrgDataPermissionDto> menus=new ArrayList<>();
	    for (SysRoleOrgDataPermissionDto menu : list) {  
	    	  //本身id
	          String menuId = menu.getOrgdepid();
	          //父id
	          String pid = menu.getParentOrgid();
	          if (parentId.equals(pid)) {  
	              List<SysRoleOrgDataPermissionDto> menuLists = buildTree(list, menuId);  
	              menu.setChildMenu(menuLists);
	              menus.add(menu);  
	          }  
	    }  
		return menus;
	}
}
